package com.conferenceroom.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.conferenceroom.dto.AjaxResult;
import com.conferenceroom.dto.ReservationRequest;
import com.conferenceroom.entity.Orders;
import com.conferenceroom.entity.Room;
import com.conferenceroom.entity.User;
import com.conferenceroom.service.OrdersService;
import com.conferenceroom.service.RoomService;
import com.conferenceroom.service.UserService;
import com.conferenceroom.vo.OrderWithCaltime;
import com.conferenceroom.vo.OrdersWithRoominfo;
import com.conferenceroom.vo.ReservationOrder;
import com.conferenceroom.vo.refundOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/orders")
public class OrdersController {

    @Autowired
    private OrdersService ordersService;
    @Autowired
    private UserService userService;
    @Autowired
    private RoomService roomService;

    //根据用户id获取所有订单，附带倒计时
    @GetMapping("/time/{id}")
    public AjaxResult getAllOrdersWithTime(@PathVariable Integer id) {
        List<OrderWithCaltime> orders = ordersService.listWithTime(id);
        return orders.isEmpty() ? AjaxResult.fail("无订单记录") : AjaxResult.success(orders);

    }

    //根据订单id获取所有订单，附带倒计时
    @GetMapping("/onetime/{orderId}")
    public AjaxResult getOrderWithCountdown(@PathVariable Integer orderId) {
        try {
            OrderWithCaltime orderWithCaltime = ordersService.getOrderWithCountdownById(orderId);
            return AjaxResult.success(orderWithCaltime);
        } catch (RuntimeException e) {
            return AjaxResult.fail(e.getMessage());
        }
    }

    @GetMapping
    public AjaxResult getAllOrders() {
        List<Orders> orders = ordersService.list(new QueryWrapper<>());
        return orders.isEmpty() ? AjaxResult.fail("无订单记录") : AjaxResult.success(orders);
    }

    @GetMapping("/{id}")
    public AjaxResult getOrderById(@PathVariable Integer id) {
        Orders orders = ordersService.getById(id);
        if (orders == null) {
            return AjaxResult.fail("订单不存在");
        }
        // 转换为ReservationOrder对象
        ReservationOrder reservationOrder = ReservationOrder.builder()
                .orderId(orders.getOrderId().toString())
                .roomName(roomService.getById(orders.getRoomId()).getRoomname())
                .startTime(orders.getStartTime())
                .endTime(orders.getEndTime())
                .username(userService.getById(orders.getUserId()).getUsername())
                .realName(userService.getById(orders.getUserId()).getRealName())
                .phone(userService.getById(orders.getUserId()).getPhone())
                .company(userService.getById(orders.getUserId()).getCompany())
                .totalFee(orders.getTotalFee())
                .build();
        return AjaxResult.success(reservationOrder);
    }

    @GetMapping("/page")
    public AjaxResult getAllOrdersByPage(@RequestParam(defaultValue = "1") Integer pageNum,
                                         @RequestParam(defaultValue = "10") Integer pageSize) {
        Page<Orders> page = new Page<>(pageNum, pageSize);
        Page<Orders> ordersPage = ordersService.page(page);
        return AjaxResult.success(ordersPage);
    }


    @PostMapping
    public AjaxResult saveOrder(@RequestBody Orders orders) {
        boolean saved = ordersService.save(orders);
        return saved ? AjaxResult.success("下单成功") : AjaxResult.fail("下单失败");
    }

    @PutMapping("/{id}")
    public AjaxResult updateOrder(@PathVariable Integer id, @RequestBody Orders orders) {
        orders.setOrderId(id);
        boolean updated = ordersService.updateById(orders);
        return updated ? AjaxResult.success("更新成功") : AjaxResult.fail("更新失败");
    }

    @DeleteMapping("/{id}")
    public AjaxResult deleteOrderById(@PathVariable Integer id) {
        boolean deleted = ordersService.removeById(id);
        return deleted ? AjaxResult.success("取消成功") : AjaxResult.fail("取消失败");
    }


    //  预约会议室后创建订单
    @PostMapping("/reserve")
    public AjaxResult createReservation(@RequestBody ReservationRequest request) {

            ReservationOrder order = ordersService.createReservation(request);
            return AjaxResult.success(order);

    }

    @PostMapping("/page/condition")
    public AjaxResult pageByCondition(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestBody Orders order) {

        Page<Orders> page = new Page<>(pageNum, pageSize);
        IPage<Orders> result = ordersService.pageByCondition(page, order);

        return AjaxResult.success(result);
    }

    // 返回倒计时（简单版）
    @GetMapping("/time-diff/{orderId}")
    public AjaxResult getTimeDifference(@PathVariable Integer orderId) {
    // 获取订单信息
    Orders order = ordersService.getById(orderId);
    if (order == null) {
        return AjaxResult.fail("订单不存在");
    }

    // 获取订单的创建时间
    Date createTime = order.getCreateTime();
    if (createTime == null) {
        return AjaxResult.fail("订单创建时间为空");
    }

    // 当前时间
    Date now = new Date();

    // 将 Date 转换为 Instant
    Instant createInstant = createTime.toInstant();
    Instant nowInstant = now.toInstant();

    // 计算时间差
    Duration duration = Duration.between(createInstant, nowInstant);

    // 提取总秒数用于判断是否超时
    long totalSeconds = duration.getSeconds();

    // 判断是否超过 30 分钟（30 * 60 = 1800 秒）
    if (totalSeconds > 1800) {
        // 超过 30 分钟，返回剩余时间为 00:00
        return AjaxResult.success("00:00");
    }

    // 否则正常计算剩余时间
    long minutes = (1800 - totalSeconds) / 60; // 剩余分钟
    long seconds = (1800 - totalSeconds) % 60; // 剩余秒数

    // 构建返回结果（格式为 mm:ss）
    String timeDifference = String.format("%02d:%02d", minutes, seconds);

    return AjaxResult.success(timeDifference);
}


    //对订单进行模拟支付操作
    @PostMapping("/pay/{orderId}")
    public AjaxResult payOrder(@PathVariable Integer orderId) {
        return ordersService.payOrder(orderId);
    }

    /**
     * 主动取消未支付的订单
     * @param orderId 订单ID
     * @return 操作结果
     */
    @PostMapping("/cancel/unpaid/{orderId}")
    public AjaxResult cancelUnpaidOrder(@PathVariable Integer orderId) {
        return ordersService.cancelUnpaidOrder(orderId);
    }

    @GetMapping("/user/{userId}")
    public AjaxResult getOrdersByUserId(@PathVariable Integer userId) {
        List<Orders> orders = ordersService.list(new QueryWrapper<Orders>().eq("user_id", userId));
        if (orders.isEmpty()) {
            return AjaxResult.fail("该用户没有订单");
        }
        // 2. 构建VO列表
        List<OrdersWithRoominfo> result = orders.stream()
                .map(order -> {
                    // 获取会议室信息（
                    Room room = roomService.getById(order.getRoomId());
                    return new OrdersWithRoominfo(
                            order,
                            room != null ? room.getRoomname() : "未知会议室",
                            room != null ? room.getRoomType() : 0
                    );
                })
                .collect(Collectors.toList());

        return AjaxResult.success(result);
    }
    @GetMapping("/refund/orders")
    public AjaxResult getRefundableOrders() {
        List<refundOrder> orders = ordersService.getRefundableOrdersWithRefundFee();
        return AjaxResult.success(orders);
    }

    /**
     * 修改订单状态
     * @param orderId 订单ID
     * @param newStatus 新的状态值
     * @return 操作结果
     */
    @GetMapping("/update/status")
    public AjaxResult updateOrderStatus(@RequestParam Integer orderId,
                                        @RequestParam Integer newStatus) {
        boolean success = ordersService.updateOrderStatusById(orderId, newStatus);
        return success ? AjaxResult.success("状态更新成功") : AjaxResult.fail("状态更新失败");
    }
    /**
     * 修改订单状态并计算退款金额
     * @param orderId 订单ID
     * @return 包含退款金额的Ajax结果
     */
    @GetMapping("/update/status/refund")
    public AjaxResult updateOrderStatusWithRefund(@RequestParam Integer orderId) {
        try {
            Integer refundFee = ordersService.updateOrderStatusWithRefund(orderId);

            if (refundFee == -1) {
                return AjaxResult.fail("距离会议开始不足24小时，不可退款");
            } else if (refundFee == 0) {
                return AjaxResult.success("订单未支付，可直接取消");
            }

            return AjaxResult.success("退款金额: " + refundFee);
        } catch (RuntimeException e) {
            return AjaxResult.fail(e.getMessage());
        }
    }

    @PostMapping("/page/by-userids")
    public AjaxResult getOrdersByUserIds(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestBody Map<String, Object> request) {

        // 获取参数
        @SuppressWarnings("unchecked")
        List<Integer> userIds = request.containsKey("userIds") ?
                (List<Integer>) request.get("userIds") : null;
        Integer paymentStatus = request.containsKey("paymentStatus") ?
                (Integer) request.get("paymentStatus") : null;

        // 构建动态查询条件
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();

        // 添加用户ID条件（如果存在）
        if (userIds != null && !userIds.isEmpty()) {
            queryWrapper.in("user_id", userIds);
        }

        // 添加支付状态条件（如果存在）
        if (paymentStatus != null) {
            queryWrapper.eq("payment_status", paymentStatus);
        }

        // 执行分页查询（如果两个参数都为空，则查询所有订单）
        Page<Orders> page = new Page<>(pageNum, pageSize);
        IPage<Orders> resultPage = ordersService.page(page, queryWrapper);

        return AjaxResult.success(resultPage);
    }



}
